#!/usr/bin/jython
from threadpool import ThreadPool
import time
import math
import sys

def isprime(n):
    """Returns True if n is prime and False otherwise"""
    if n < 2:
        return False
    if n == 2:
        return True
    max = int(math.ceil(math.sqrt(n)))
    i = 2
    while i <= max:
        if n % i == 0:
            return False
        i += 1
    return True

def sum_primes(n):
    """Calculates sum of all primes below given integer n"""
    sum = 0L
    for x in xrange(2,n):
        if isprime(x):
            sum += x
    return (n, sum)

def taskCallback(data):
    print "Callback called for", data

if __name__ == "__main__":
    if len(sys.argv) > 1:
        threads = sys.argv[1]
    else:
        threads = 1

    start_time = time.time()

    pool = ThreadPool(threads)

    # Insert tasks into the queue and let them run
    for x in xrange(100000, 1000000, 10000):
        pool.queueTask(sum_primes, x, taskCallback)

    # When all tasks are finished, allow the threads to terminate
    pool.joinAll()

    print "Time elapsed: ", time.time() - start_time, "s"
